<template>
  <div>
    <!-- 查询条件 -->
    <el-form :model="ruleForm" ref="form" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="6" :offset="0">
          <el-form-item label="供应商:" prop="organId">
            <el-select v-model="ruleForm.organId" placeholder="选择供应商"
            v-bind:disabled="!!ruleForm.linkNumber">
              <el-option
                v-for="item in suppliers"
                :key="item.supId"
                :label="item.supName"
                :value="item.supId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-form-item label="单据日期:" prop="billDate">
            <el-date-picker
              type="datetime"
              v-model="ruleForm.billDate"
              placeholder="选择日期与时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              clearable
              class="input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-form-item label="单据编号:">
            <el-input v-model="ruleForm.number" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-form-item label="关联订单">
            <el-input v-model="ruleForm.linkNumber" readonly suffix-icon="Search" placeholder="请选择关联订单"
            v-perm:purchase:back:insert:LinkedOrder="handleIconClick" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <div class="ant-row-flex" style="display: flex; align-items: center">
        <div class="ant-col" style="margin-right: 10px">
          <el-button
            type="primary"
            @click="insertTr"
            class="ant-btn ant-btn-primary"
            v-if="!ruleForm.linkNumber"
          >
            <el-icon class="el-icon-left">
              <Plus />
            </el-icon>
            <span>插入行</span>
          </el-button>
        </div>
      </div>
    <!-- 选项表格 -->
    <el-table
      class="my-custom-table"
      :data="tableData"
      show-summary
      :summary-method="getSummaries"
      max-height="340"
    >
      <el-table-column type="selection" width="30" />
      <el-table-column label="仓库名称" width="100" >
        <template #default="{ row }">
            <el-select v-model="row.depId">
              <el-option v-for="item in depots"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="barcode" label="条码" width="160">
        <template #default="{ row }">
          <el-input v-model="row.barCode">
            <template #append v-if="!ruleForm.linkNumber">
              <el-button
                v-perm:purchase:back:insert:materialInsert="Saleinorder"
                ><el-icon>
                  <Search /> </el-icon
              ></el-button>
            </template>
          </el-input>
        </template>
      </el-table-column>
      <el-table-column label="名称" width="160">
        <template #default="{ row }">
          <el-input v-model="row.materialName" class="dashed-input"> </el-input>
        </template>
      </el-table-column>
      <el-table-column label="规格" property="shopCode">
        <template #default="{ row }">
          <el-input v-model="row.standard" class="dashed-input"> </el-input>
        </template>
      </el-table-column>
      <el-table-column label="库存">
        <template #default="{ row }">
          <el-input v-model="row.totalOperNumber" class="dashed-input">
          </el-input>
        </template>
      </el-table-column>
      <el-table-column label="单位">
        <template #default="{ row }">
          <el-input v-model="row.commodityUnit" class="dashed-input">
          </el-input>
        </template>
      </el-table-column>
      <el-table-column label="数量">
        <template #default="{ row }">
          <el-input  @input="change(row)" v-model="row.operNumber"> </el-input>
        </template>
      </el-table-column>
      <el-table-column label="单价">
        <template #default="{ row }">
          <el-input @input="change(row)" v-model="row.wholesaledecimal"> </el-input>
        </template>
      </el-table-column>
      <el-table-column label="金额">
        <template #default="{ row }">
          <el-input  v-model="row.allPrice"> </el-input>
        </template>
      </el-table-column>
      <el-table-column label="税率">
        <template #default="{ row }">
          <el-input @input="change(row)" placeholder="%" v-model="row.taxRate"> </el-input>
        </template>
      </el-table-column>
      <el-table-column label="税额">
        <template #default="{ row }">
          <el-input v-model="row.taxMoney" class="dashed-input"> </el-input>
        </template>
      </el-table-column>
      <el-table-column label="价税合计">
        <template #default="{ row }">
          <el-input v-model="row.taxLastMoney"> </el-input>
        </template>
      </el-table-column>
      <el-table-column label="备注">
        <template #default="{ row }">
          <el-input v-model="row.remark"> </el-input>
        </template>
      </el-table-column>
    </el-table>
      <el-form-item style="margin-top: 5px">
        <el-input
          v-model="ruleForm.remark"
          :autosize="{ minRows: 1, maxRows: 4 }"
          type="textarea"
          placeholder="请输入备注"
        />
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="6" :offset="0">
          <el-form-item label="优惠率：">
            <el-input v-model="ruleForm.discountRate" placeholder="请输入优惠率">
              <template #suffix>
                <span>%</span>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-form-item label="付款优惠：">
            <el-input v-model="ruleForm.paymentDiscount" placeholder="请输入付款优惠"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-form-item label="优惠后金额：">
            <el-input v-model="ruleForm.discountedAmount" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-form-item label="其它费用：">
            <el-input v-model="ruleForm.otherMoney" placeholder="请输入其它费用"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-form-item label="结算账户：" prop="accountId">
            <el-select v-model="ruleForm.accountId" placeholder="选择结算账户">
              <el-option
                v-for="item in accounts"
                :key="item.accId"
                :label="item.name"
                :value="item.accId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-form-item label="本次付款：">
            <el-input v-model="ruleForm.documentnumber"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="0">
          <el-form-item label="本次欠款：">
            <el-input v-model="ruleForm.debt" readonly></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="height: 30px">
        <el-col :span="24" :offset="0">
          <el-form-item style="float: right">
            <el-button @click="close">取消</el-button>
            <el-button @click="submitForm(form,1)">保存并审核</el-button>
            <el-button type="primary" @click="submitForm(form,0)">保存</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 弹窗 -->
    <el-dialog
      :destroy-on-close="true"
      :title="title"
      v-model="visible"
      width="65%"
      top="15vh"
      style="height: 750px"
    >
      <router-view
        @close="closeAdd"
        @saveSaleinorder="saveSaleinorder"
        @subdocument="subdocument"
        :data="data"
      ></router-view>
    </el-dialog>
  </div>
</template>

<script setup>
// 导入Vue中的ref和defineEmits函数
import { ref, defineEmits, onMounted } from "vue";
// 使用defineEmits函数定义可以触发的自定义事件
import request from "@/api/request";
import router from "@/router";
import { Search } from "@element-plus/icons-vue";
import { ElMessage } from 'element-plus';

let emits = defineEmits(["close"]);
let tableData = ref([{ 
    operNumber: 0,
    allPrice: 0,
    taxMoney: 0,
    taxLastMoney: 0
}]);
let title = ref("");
let form = ref();
let visible = ref(false);
let data = ref({});
//供应商
let suppliers = ref([]);
//结算用户
let accounts = ref([]);
//仓库
let depots = ref([]);
//单据信息
let ruleForm = ref({
  discountRate: 0,
  paymentDiscount: 0,
  discountedAmount: 0,
  documentnumber: 0,
  otherMoney: 0,
  debt: 0
});
//插入一条数据
let insertTr = () => {
  tableData.value.push({
    operNumber: 0,
    allPrice: 0,
    taxMoney: 0,
    taxLastMoney: 0
  });
};

//校验规则
let rules = {
  organId: [
    { required: true, message: '请选择供应商！', trigger: 'change' }
  ],
  billDate: [
    { required: true, message: '请选择单据日期和时间！', trigger: 'change' }
  ],
  accountId: [
    { required: true, message: '请选择结算账户！', trigger: 'change' }
  ]
}

// 使用 onMounted 生命周期钩子来设置初始日期和时间
onMounted(() => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  ruleForm.value.billDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
});

//表格合计
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  sums[0] = "合计";
  const operNumbers = data.map((item) => Number(item['operNumber']));
  const allPrices = data.map((item) => Number(item['allPrice']));
  const taxMoneys = data.map((item) => Number(item['taxMoney']));
  const taxLastMoneys = data.map((item) => Number(item['taxLastMoney']));
  let numberTotal = 0;
  let allPriceTotal = 0;
  let taxMoneyTotal = 0;
  let taxLastMoneyTotal = 0;
  operNumbers.forEach(item=>{
    numberTotal+=item
  })
  allPrices.forEach(item=>{
    allPriceTotal+=item
  })
  taxMoneys.forEach(item=>{
    taxMoneyTotal+=item
  })
  taxLastMoneys.forEach(item=>{
    taxLastMoneyTotal+=item
  })
  sums[7] = numberTotal
  sums[9] = allPriceTotal
  sums[11] = taxMoneyTotal
  sums[12] = taxLastMoneyTotal

  ruleForm.value.paymentDiscount = (ruleForm.value.discountRate*0.01) * taxLastMoneyTotal
  ruleForm.value.discountedAmount = taxLastMoneyTotal - ruleForm.value.paymentDiscount
  ruleForm.value.debt = Number(ruleForm.value.discountedAmount) + Number(ruleForm.value.otherMoney) - Number(ruleForm.value.documentnumber)
  return sums;
};

//input计算绑定
let change = (row)=>{
  row.allPrice = row.operNumber * row.wholesaledecimal
  row.taxMoney = (row.taxRate*0.01) * row.allPrice
  row.taxLastMoney = row.taxMoney + row.allPrice
}

//关闭商品选择页面
let closeAdd = () => {
  visible.value = false;
};
let close = () => {
  emits("close");
};

//查询供应商
let findsuppliers = () =>{
  request({
    url:'/basic/vendor/findByStatus',
    method: 'get',
    params:{
      supType: 0
    }
  }).then(resp =>{
    suppliers.value = resp.data
  })
}
findsuppliers();

//查询仓库
let loadDepot = () => {
    request({
        url: '/basic/depot/findByEnabled',
        method: 'get'
    }).then(res => {
        depots.value = res.data;
    }).catch(err => {
        console.error(err);
    });
};
loadDepot();

//查询结算用户
let findaccounts = () => {
  request({
    url: "/basic/account/findByStatus",
    method: "get",
  }).then((resp) => {
    accounts.value = resp.data;
    // 查找默认结算账
    let defaultAccount = accounts.value.find(account => account.isDefault === 1);
    if (defaultAccount) {
      ruleForm.value.accountId = defaultAccount.accId;
    }
  });
};
findaccounts();

//弹出商品选择
let Saleinorder = (menu) => {
  title.value = menu.cname;
  visible.value = true;
  router.push(menu.path);
};

//关联订单
let handleIconClick= (p) => {
  title.value = p.cname;
  visible.value = true;
  router.push(p.path);
}

//生成单据编号
onMounted(() => {
  // 从本地存储获取当前的订单编号，如果不存在则默认为1
  let currentOrderNumber = parseInt(
    localStorage.getItem("purchaseD") || "1",
    10
  );

  // 自增
  currentOrderNumber++;

  // 设定编号前缀
  const prefix = "CGTH";

  // 确定后缀的长度，使得整个编号的长度达到一定的要求（这里假设总长度为12，前缀为4，所以后缀为8）
  const suffixLength = 8;

  // 格式化为指定长度的字符串，不足部分用0填充
  const formattedSuffix = currentOrderNumber
    .toString()
    .padStart(suffixLength, "0");

  // 生成完整的订单编号
  const formattedOrderNumber = `${prefix}${formattedSuffix}`;

  // 将生成的订单编号赋值到表单（假设ruleForm.value是一个响应式对象）
  ruleForm.value.number = formattedOrderNumber;

  // 将新的订单编号存储到本地存储中，便于下次使用（只存储数字部分，因为前缀是固定的）
  localStorage.setItem("purchaseD", currentOrderNumber.toString());
});

// 接收并显示保存的数据
let saveSaleinorder = (selectedItems) => {
  tableData.value = selectedItems.map((item) => ({
    barCode: item.barCode,
    categoryName: item.categoryName,
    color: item.color,
    commodityUnit: item.commodityUnit,
    materialName: item.materialName,
    mfrs: item.mfrs,
    model: item.model,
    sku: item.sku,
    standard: item.standard,
    totalIn: item.totalIn,
    remark: item.remark,
    totalOperNumber: item.totalOperNumber,
    totalOut: item.totalOut,
    wholesaledecimal: item.wholesaledecimal,
    basicnumber: item.basicnumber,
    allprice: item.allprice,
    mid: item.mid,
    aid: item.aid,
    operNumber: 1,
    allPrice: 1*item.wholesaledecimal,
    taxRate: 0,//税率
    taxMoney: 0,//税额
    taxLastMoney: item.wholesaledecimal//价税合计
  }));
};

//接收关联订单数据
let subdocument = (items,header) => {
  console.log("items",items);
  console.log("header",header);
  ruleForm.value.organId = header.supId
  ruleForm.value.linkNumber = header.number
  ruleForm.value.accountId = header.accountId
  ruleForm.value.discountRate = header.discount
  tableData.value = items.map((item) => ({
    barCode: item.barCode,
    commodityUnit: item.materialUnit,
    materialName: item.name,
    depId: item.depotId,
    sku: item.sku,
    standard: item.standard,
    remark: item.remark,
    totalOperNumber: item.totalOperNumber,
    wholesaledecimal: item.unitPrice,
    basicnumber: item.basicnumber,
    allPrice: item.allPrice,
    operNumber: item.operNumber,
    linkId: item.id,
    mid: item.materialId,
    aid: item.materialExtendId,
    taxRate: item.taxRate,//税率
    taxMoney: item.taxMoney,//税额
    taxLastMoney: item.taxLastMoney//价税合计
  }));
};

const submitForm = (formEl,status) => {
  const data = {
    //主表添加数据
    erpDepotHead: {
      type:"出库",
      subType:"采购退货",
      defaultNumber : ruleForm.value.number,
      number: ruleForm.value.number,
      createTime: ruleForm.value.billDate,
      operTime: ruleForm.value.billDate,
      organId: ruleForm.value.organId,
      accountId: ruleForm.value.accountId,
      linkNumber: ruleForm.value.linkNumber,
      remark: ruleForm.value.remark,
      changeAmount: ruleForm.value.documentnumber,//支付定金
      totalPrice: tableData.value.reduce((total, row) => total + parseFloat(row.allPrice || 0),0), // 计算合计金额
      discount: ruleForm.value.discountRate,//优惠率
      discountMoney: ruleForm.value.paymentDiscount,//优惠金额
      discountLastMoney: ruleForm.value.discountedAmount,//优惠后金额
      otherMoney: ruleForm.value.otherMoney,//其它费用
      status: status,
    },
    //附表添加数据
    erpDepotItems: tableData.value.map((row) => ({
      depotId: row.depId,
      materialId: row.mid,
      materialExtendId: row.aid,
      materialUnit: row.commodityUnit,
      sku: row.sku,//多属性
      operNumber: row.operNumber,//数量
      basicNumber: row.operNumber,
      unitPrice: row.wholesaledecimal,//单价
      allPrice: row.allPrice,
      remark: row.remark,
      linkId: row.linkId,
      taxRate: row.taxRate,//税率
      taxMoney: row.taxMoney,//税额
      taxLastMoney: row.taxLastMoney//价税合计
    })),
  };
  formEl.validate(valid =>{
    if(valid) {
      //发送请求
      request({
        url: "/purchase/order/insert",
        method: "post",
        data: data,
      }).then((res) => {
          close();
          ElMessage.success(res.data);
        }).catch((err) => {
          ElMessage.error("提交失败: " + (err.message || "请稍后重试"));
        });
      }
    })
};
</script>

<style scoped>
/* 增加表格单元格的内边距（上下左右都增加） */
::v-deep .el-table .cell {
  padding: 1px;
}

.my-custom-table .el-table__summary-row {
  /* 这里的样式将只应用于具有 my-custom-table 类的表格的合计行 */
  background-color: white;
  /* 示例背景色 */
}

.dashed-input {
  user-select: none;
  /* 禁止文本选择 */
  pointer-events: none;
  /* 禁止交互，如点击 */
}
</style>
